#!/bin/sh
set -e

# 当前目录
CURRENT_DIR=$(
   cd "$(dirname "$0")"
   pwd
)
nowDate=$(date +'%Y%m%d%H%M')



# 旧版本镜像 中间空格分割
oldImages=(OLDIMAGES)
# 新版本镜像 中间空格分割
newImages=(NEWIMAGES)
# 导出包的名字
outPutName="app.tar.gz"

# 是否拉取镜像
isPullImages=ISPULL

# 拉取镜像
pullImages(){
	if [[ $isPullImages == "true" ]]; then
		echo "拉取旧版本镜像"
		for oldImage in ${oldImages[*]}
		do
			docker pull ${oldImage}
		done
		
		echo "拉取新版本镜像"
		for newImage in ${newImages[*]}
		do
			docker pull ${newImage}
		done
		
		echo "拉取镜像结束"
	fi
}

packageImage(){
	path=$1
	flag=$2

	images=()
	mkdir -p $path && cd $path
	if [[ $flag == "old" ]];then
		images=${oldImages[*]}
	else
		images=${newImages[*]}
	fi
	echo "打包 镜像${images[*]}" 
	docker save -o  $path/images.tar ${images[*]} 
	tar -xf images.tar  -C . && ls -l |grep ^d  > /dev/null && rm -rf images.tar
}

checkFile(){
	oldPath=$1
	newPath=$2
	oldFileNams=$(ls $oldPath)
	newFileNams=$(ls $newPath)
	
	for newImage in $newFileNams
	do
		if [[ "${oldFileNams[@]}"  =~ "${newImage}" ]] && [[ "$newImage" != "repositories" ]]&& [[ "$newImage" != "manifest.json" ]] && [[ "$newImage" !=  *.json ]]
		then
			rm -rf $newPath/$newImage
			echo "相同(same) $newPath/$newImage"
		else
			echo "不相同 $newImage"
		fi
	done
	cd $newPath && tar -zvcf $CURRENT_DIR/$outPutName *
	rm -rf $newPath
	rm -rf $oldPath
}

main(){
	# 拉取镜像
	pullImages
	
	oldPath=$CURRENT_DIR/oldImages
	newPath=$CURRENT_DIR/newImages
	
	# 打包旧的
	packageImage $oldPath old
	# 打包新的
	packageImage $newPath new
	# 检查不同的，删除相同的，打包新的
	checkFile $oldPath $newPath
	
}

main
